package com.imagine;

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class AdViewService extends Service {

  private WindowManager windowManager;
  public static AdView adView;

  @Override public IBinder onBind(Intent intent) {
    // Not used
    return null;
  }

  @Override public void onCreate() {
    super.onCreate();

  }

 
  @Override
        public int onStartCommand(Intent intent, int flags, int startId) {

            try {
                if (adView != null) windowManager.removeView(adView);
                } catch (Exception e) {}
         
            if(adView != null){
                adView.loadAd(new AdRequest());
                Animation alpha = new AlphaAnimation(.65f, .65f);
                alpha.setFillAfter(true);
                alpha.setFillBefore(true);
                adView.startAnimation(alpha);

                    windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
                    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                            WindowManager.LayoutParams.WRAP_CONTENT,
                            WindowManager.LayoutParams.WRAP_CONTENT,
                            WindowManager.LayoutParams.TYPE_PHONE,
                            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                            PixelFormat.TRANSLUCENT);

                        params.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
                        params.x = 0;
                        params.y = 0;

                        windowManager.addView(adView, params);
            }
                return super.onStartCommand(intent, flags, startId);
        }
 
  @Override
  public void onDestroy() {
    super.onDestroy();
    try {
        if (adView != null) windowManager.removeView(adView);
    } catch (Exception e) {}
    adView = null;
  }
}
